package com.bwie.init;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.common.domain.GlobalStatusEnum;
import com.bwie.common.domain.request.ShopListRequest;
import com.bwie.common.domain.response.ShopListResponse;
import com.bwie.common.result.PageResult;
import com.bwie.common.result.Result;
import com.bwie.domain.EsShop;
import com.bwie.exception.EsShopException;
import com.bwie.mapper.EsShopMapper;
import com.bwie.remote.RemoteShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺信息初始化
 *
 * @author <a href="mailto:3364114353@qq.com">liuwenliang</a>
 * @version 1.0
 * @description: 店铺信息初始化
 * @date 2025/9/9 12:06
 */
@Component
public class ShopDataInit implements ApplicationRunner {

    @Autowired
    private RemoteShopService remoteShopService;

    @Autowired
    private EsShopMapper esShopMapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //获取所有店铺信息（远程调用）
        Result<PageResult<ShopListResponse>> shopListResult = remoteShopService.getShopList(new ShopListRequest());
        int code = shopListResult.getCode();
        if (code == GlobalStatusEnum.SYSTEM_IS_BUSY.getCode()) {
            throw new EsShopException(GlobalStatusEnum.SYSTEM_IS_BUSY.getLabel());
        }
        PageResult<ShopListResponse> data = shopListResult.getData();
        List<ShopListResponse> shopList = data.getList();
        //类型转换
        List<EsShop> esShops = new ArrayList<>();
        List<EsShop> esShopList = shopList.stream()
                .map(shops -> {
                    EsShop esShop = new EsShop();
                    BeanUtil.copyProperties(shops, esShop);
                    return esShop;
                }).collect(Collectors.toList());
        esShopMapper.insertBatch(esShopList);

    }
}
